from sqlalchemy import Column, Integer, String, Text, ForeignKey
from sqlalchemy.orm import relationship, backref

from db_util import Base, Session, engine


class LoginUser(Base):
    __tablename__ = 't_user_login'
    id = Column(Integer, primary_key=True, autoincrement=True)
    uname = Column(String(32), nullable=False)
    passwd = Column(String(32), nullable=False)

    # user = relationship('User',uselist=False) # 不友好，总有警告

    def __repr__(self):
        return f'<User: id={self.id} uname={self.uname} passwd={self.passwd}>'


# 创建1对1的关系, 创建一个字段来做别一个表的标识(外键)
class User(Base):
    __tablename__ = 't_user'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(32), nullable=False, name='name')
    gender = Column(String(1))
    address = Column(String(64))

    login_id = Column(Integer,ForeignKey('t_user_login.id'))
    login_user = relationship('LoginUser',backref=backref('user',uselist=False))

    def __repr__(self):
        return f'<User: id={self.id} name={self.name} gender={self.gender} address={self.address}>'

def create_data():
    login = LoginUser(uname='sxt',passwd='123')
    user = User(name='尚学堂',gender='男',address='北京')
    login.user = user #建立关联关系

    with Session() as ses:
        ses.add(login)
        ses.commit()

if __name__ == '__main__':
    # Base.metadata.create_all(engine)
    create_data()
